{% extends 'layout/manage.html' %}
{% load static %}

{% block css %}
    <style>
        .panel-default .panel-heading {
            display: flex;
            flex-direction: row;
            justify-content: space-between;
        }

        .panel-default > .panel-heading a {
            text-decoration: none;
        }

        .panel-default > .panel-heading span {
            padding: 0 5px;
        }

        .panel-default > .panel-heading .function .upload {
            overflow: hidden;
        }

        .panel-default > .panel-heading .function .upload input {
            opacity: 0;
            position: absolute;
            top: 0;
            bottom: 0;
            width: 76px;
            left: -2px;
            overflow: hidden;
        }

        .upload-progress {
            position: fixed;
            right: 15px;
            bottom: 10px;
            width: 400px;
        }

        .progress {
            width: 370px;
        }

        .upload-progress .progress-error {
            color: red;
        }
    </style>
{% endblock %}
{% block content %}
    <div class="container-fluid">
        <div class="panel panel-default">
            <!-- Default panel contents -->
            <div class="panel-heading">
                <div>
                    <i class="fa fa-home" aria-hidden="true"></i>
                    <a href="{% url 'file' project_id=request.bug_platform.project.id %}">
                        <span>文件库</span>
                    </a>
                    {% for breadcrumb in breadcrumb_list %}
                        <i class="fa fa-angle-double-right" aria-hidden="true"></i>
                        <a href="{% url 'file' project_id=request.bug_platform.project.id %}?folder={{ breadcrumb.id }}">
                            <span>{{ breadcrumb.name }}</span>
                        </a>
                    {% endfor %}
                </div>
                <div class="function">
                    <div class="btn btn-primary btn-xs upload" style="position: relative">
                        <div><i class="fa fa-upload" aria-hidden="true"></i> 上传文件</div>
                        <input type="file" multiple name="uploadFile" id="uploadFile">
                    </div>
                    <a href="#" class="btn btn-primary btn-xs" data-toggle="modal" data-target="#addModal" data-whatever="新建文件夹">
                        <i class="fa fa-plus-circle" aria-hidden="true"></i> 新建文件夹
                    </a>
                    {#                    <a href="#" class="btn btn-primary btn-xs" data-toggle="modal" data-target="#addModal" data-whatever="编辑文件夹">#}
                    {#                        <i class="fa fa-plus-circle" aria-hidden="true"></i> 编辑文件夹#}
                    {#                    </a>#}
                </div>
            </div>

            <!-- Table -->
            <table class="table">
                <thead id="Thead">
                <tr>
                    <th>名称</th>
                    <th>文件大小</th>
                    <th>更新者</th>
                    <th>更新时间</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody id="rowList">
                {% for item in file_object_list %}
                    <tr>
                        <td>
                            {% if item.file_type == '2' %}
                                <a href="{% url 'file' project_id=request.bug_platform.project.id %}?folder={{ item.id }}" style="color: black">
                                    <i class="fa fa-folder" aria-hidden="true"></i>{{ item.name }}
                                </a>
                            {% else %}
                                <i class="fa fa-file-audio-o" aria-hidden="true"></i>{{ item.name }}
                            {% endif %}
                        </td>
                        <td>
                            {% if item.file_type == '1' %}
                                {{ item.file_size }}
                            {% else %}
                                ---
                            {% endif %}
                        </td>
                        <td>{{ item.update_user.username }}</td>
                        <td>{{ item.update_datetime }}</td>
                        <td>
                            {% if item.file_type == '2' %}
                                <a class="btn btn-default btn-xs"
                                   data-toggle="modal"
                                   data-target="#addModal"
                                   data-name="{{ item.name }}"
                                   data-fid="{{ item.id }}"
                                   data-whatever="修改文件夹">
                                    <i class="fa fa-edit" aria-hidden="true"></i>
                                </a>
                                {#                                <a class="btn btn-danger btn-xs"#}
                                {#                                   data-toggle="modal"#}
                                {#                                   data-fid="{{ item.id }}"#}
                                {#                                   data-target="#delModal">#}
                                {#                                    <i class="fa fa-trash-o fa-lg"></i>#}
                                {#                                </a>#}
                            {% else %}
                                <a class="btn btn-default btn-xs download"
                                   href="{% url 'file_download' project_id=request.bug_platform.project.id file_id=item.id %}">
                                    <i class="fa fa-cloud-download" aria-hidden="true"></i>
                                </a>
                            {% endif %}

                            {#                                <a class="btn btn-danger btn-xs delete"><i class="fa fa-trash" aria-hidden="true"></i></a>#}
                            <a class="btn btn-danger btn-xs"
                               data-toggle="modal"
                               data-fid="{{ item.id }}"
                               data-target="#delModal">
                                <i class="fa fa-trash-o fa-lg"></i>
                            </a>
                        </td>
                    </tr>
                {% endfor %}
                </tbody>
            </table>
        </div>
    </div>

    <div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="myModalLabel">Modal title</h4>
                </div>
                <div class="modal-body">
                    <form id="formAdd" enctype="multipart/form-data">
                        <input class="hide" type="text" name="fid" id="fid">
                        {% csrf_token %}
                        {% for item in form %}
                            <div class="form-group">
                                <label for="{{ item.id_for_label }}">{{ item.label }}</label>
                                {{ item }}
                                <span class="error-msg">{{ item.errors.0 }}</span>
                            </div>
                        {% endfor %}
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">取 消</button>
                    <button id="btnFormSubmit" type="button" class="btn btn-primary">确 定</button>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="delModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-body">
                <div class="alert alert-danger alert-dismissible fade in" role="alert">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
                    <h3>是否确定要删除</h3>
                    <p>文件夹中包含所有的文件都会被删除。</p>
                    <p style="text-align: right">
                        <a class="btn btn-default btn-xs" data-dismiss="modal" aria-label="Close">取 消</a>
                        <button id="btnDelete" type="button" class="btn btn-danger btn-xs">确定</button>
                    </p>
                </div>
            </div>
        </div>
    </div>
    {#    上传精度#}
    <div id="uploadProgress" class="upload-progress hide">
        <div class="panel panel-danger">
            <div class="panel-heading">
                <i class="fa fa-cloud-upload" aria-hidden="true"> 上传进度</i>
            </div>

            <div class="panel-body">
                <table>
                    <tbody id="progressList">
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    {#    进度条#}
    <div class="hide">
        <table id="progressTemplate">
            <tbody>
            <tr>
                <td>
                    <div class="name"></div>
                    <div class="progress">
                        <div class="progress-bar progress-bar-success progress-bar-striped"
                             role="progressbar"
                             aria-valuenow="0" aria-valuemin="0"
                             aria-valuemax="100" style="width: 0%;">
                            0%
                        </div>
                    </div>
                    <div class="progress-error"></div>
                </td>
            </tr>
            </tbody>
        </table>
    </div>
    {#    文件 显示下载#}
    <div class="hide">
        <table id="rowTpl">
            <tr>
                <td>
                    <i class="fa fa-file" aria-hidden="true"></i>
                    <span class="name"></span>
                </td>
                <td class="file_size"></td>
                <td class="update_user_username"></td>
                <td class="update_datetime"></td>
                <td>
                    <a class="btn btn-default btn-xs download">
                        <i class="fa fa-cloud-download" aria-hidden="true"></i>
                    </a>
                    <a class="btn btn-danger btn-xs delete">
                        <i class="fa fa-trash" aria-hidden="true"></i>
                    </a>
                </td>
            </tr>
        </table>
    </div>
{% endblock %}

{% block js %}
    <script src="{% static 'js/cos-js-sdk-v5.min.js' %}"></script>
    <script>
        var FOLDER_URL = "{% url 'file' project_id=request.bug_platform.project.id %}";
        var FILE_DELETE_URL = "{% url 'file_delete' project_id=request.bug_platform.project.id %}";
        var COS_CREDENTIAL = "{% url 'cos_credential' project_id=request.bug_platform.project.id %}"
        var FILE_POST = "{% url 'file_post' project_id=request.bug_platform.project.id %}"
        var CURRENT_FOLDER_ID = '{{ folder.id }}'   // 页面文件夹id


        $(function () {
            // 初始化
            intiModel();
            btnModelSubmit();
            btnDeleteSubmit();
            btndUploadFile();
        });

        // 获取临时凭证【放在外面 有效期过了 自动再次获取
        // var COS_OBJECT = new COS
        /*
        上传文件
        * */
        function btndUploadFile() {
            // 获取cos的临时凭证
            $("#uploadFile").change(function () {

                // 每次上传都情空表的tr
                {#$('#progressList').empty()#}

                // 可以放在里面， 但每次上传都要去获取临时凭证
                var fileList = $(this)[0].files;

                // 获取 本次要上传的文件名字和大小
                var checkFileList = []
                $.each(fileList, function (index, fileObject) {
                    // console.log(fileObject.name);
                    var fileNmae = fileObject.name;     // 文件名字
                    var fileSize = fileObject.size;     // 文件大小
                    {#console.log(fileNmae, fileSize)#}
                    checkFileList.push({'name': fileNmae, 'size': fileSize})        // 添加数据到checkFileList列表
                    // 上传文件 （异步）
                });
                // 把上传文件的名字和大小数据发送到django后台，后台在进行容量的校验，如果没有问题 返回临时凭证在上传，否则返回错误信息
                // 获取临时凭证
                var cos_object = new COS({
                    getAuthorization: function (options, callback) {
                        // django后台发送请求，获取临时凭证
                        $.post(COS_CREDENTIAL, JSON.stringify(checkFileList),
                            // 不能传复杂的数据，只能传字典
                            // 复杂数据需转化
                            // data: JSON.stringify(checkFileList) // json 数据
                            {#$.get(' http://127.0.0.1:8000/cos/credential'), {#}
                            // 可以 options 取需要的参数
                            function (res) {
                                console.log(res)
                                if (res.status) {
                                    // 表示成功
                                    var credentials = res.data && res.data.credentials;
                                    // if (!res.data || !credentials) return console.error('credentials invalid');    // 校验 提示
                                    callback({
                                        TmpSecretId: credentials.tmpSecretId,
                                        TmpSecretKey: credentials.tmpSecretKey,
                                        XCosSecurityToken: credentials.sessionToken,
                                        StartTime: res.data.startTime,
                                        ExpiredTime: res.data.expiredTime,
                                    });

                                    // 获得临时凭证后显示进度条[ 去掉属性hide
                                    $('#uploadProgress').removeClass('hide')

                                } else {
                                    alert(res.error)
                                }
                            })
                    }
                });

                // 上传文件 （异步）【上传之前要获取临时凭证
                $.each(fileList, function (index, fileObject) {
                    // console.log(fileObject.name);
                    var fileNmae = fileObject.name;     // 文件名
                    var fileSize = fileObject.size;     // 文件大小
                    var key = Date.now() + '_' + fileNmae;       // 随机名字存到cos中, 为了防止重名

                    {#alert(key)#}
                    // alert((window.location.search).split('=')[1]);  // 获取文件夹的 folder= '25'
                    // var parent = (window.location.search).split('=')[1]

                    // clone() 克隆
                    var $tr = $('#progressTemplate').find('tr').clone();
                    $tr.find('.name').text(fileNmae);    // 修改名字
                    $('#progressList').append($tr)


                    // 上传文件
                    // 上传文件 （异步）
                    cos_object.putObject({
                        Bucket: '{{ request.bug_platform.project.bucket }}',
                        Region: '{{ request.bug_platform.project.region }}',
                        Key: key,
                        {#Key: ffileNmae,#}
                        // StorageClass: 'STANDARD',
                        Body: fileObject,   // 上传的文件对象
                        onProgress: function (progressData) {
                            console.log('文件上传进度--->', fileNmae,)
                            {#var dataDict = JSON.stringify(progressData);#}
                            // 拿到百分比
                            var percent = progressData.percent * 100 + '%';
                            $tr.find('.progress-bar').text(percent);  // 动态修改文本
                            $tr.find('.progress-bar').css('width', percent)     // 动态修改css样式大小
                        }
                    }, function (err, data) {
                        console.log(err || data);

                        // 上传成功
                        if (data && data.statusCode == 200) {
                            // 上传成功 将本次文件提交到后台 并 写入数据库

                            $.post(FILE_POST, {     // url
                                    'name': fileNmae,
                                    'file_size': fileSize,
                                    'key': key,
                                    'parent': CURRENT_FOLDER_ID,
                                    'file_path': data.Location,
                                    'etag': data.ETag,
                                },         // 要向后端传的数据
                                function (res) {    // 回调函数
                                    {#console.log(res);#}
                                    // 在数据库中保存的数据在页面展示出来
                                    var newTr = $("#rowTpl").find('tr').clone();  //克隆
                                    // $('#Thead').append(newTr)
                                    newTr.find('.name').text(res.data.name);
                                    newTr.find('.file_size').text(res.data.file_size + 'KB');
                                    newTr.find('.update_user_username').text(res.data.update_user__username);
                                    newTr.find('.update_datetime').text(res.data.datetime);
                                    newTr.find('.download').attr('href', res.data.download_url);

                                    $('#rowList').append(newTr);

                                    // 自己的进度条删除
                                    $tr.remove();

                                })
                        } else {
                            // 错误提示
                            $tr.find('.progress-error').text(error);

                        }
                    });
                });

            });
        }


        /*
        删除
        * */
        function btnDeleteSubmit() {
            $('#btnDelete').click(function () {
                // 删除要获取要删除数据的ID
                $.ajax({
                    url: FILE_DELETE_URL,
                    type: "GET",
                    data: {fid: $(this).attr("fid")},
                    {#data: {"fid": '2'},#}
                    {#dataType: "JSON",#}
                    success: function (res) {
                        {#console.log(res)#}
                        if (res.status) {
                            // 成功后刷新页面
                            window.location.reload();  //刷新页面
                        }
                    }
                });
            });
        }


        /*
        表单
        * */
        function btnModelSubmit() {
            $('#btnFormSubmit').click(function () {
                $.ajax({
                    //uri: FOLDER_URL,
                    // location.href 获取当前页面的url
                    uri: location.href,
                    type: "POST",
                    data: $("#formAdd").serialize(),   // 拿到所有
                    dataType: "JSON",
                    success: function (res) {
                        console.log(res)
                        if (res.status) {
                            // 成功后就刷新页面
                            // location.href = location.href;
                            {#console.log(location.href)#}
                            history.go(0);
                        } else {
                            $.each(res.error, function (key, value) {
                                $('#id_' + key).next().text(value[0])
                            });
                        }
                    }
                });
            });
        }


        /*
        初始化
        * */
        function intiModel() {
            $('#addModal').on('show.bs.modal', function (event) {
                var button = $(event.relatedTarget); // Button that triggered the modal
                var recipient = button.data('whatever'); // Extract info from data-* attributes
                var name = button.data('name');
                var fid = button.data('fid');

                var modal = $(this);
                modal.find('.modal-title').text(recipient);

                if (fid) {
                    {#// 有值就是编辑#}
                    {#$("#id_name").val(name);  === #}
                    modal.find("#id_name").val(name);

                    modal.find("#fid").val(fid);
                } else {
                    {#// 新建#}
                    modal.find('.error-msg').empty();   // 清除错误信息
                    {#// 情除输入框#}
                    {#// document.getElementById('formAdd').reset()  ===#}
                    $("#formAdd")[0].reset()
                    {#// modal.find('.modal-body input').val(recipient)#}
                }
            });

            $('#delModal').on('show.bs.modal', function (event) {
                var button = $(event.relatedTarget); // Button that triggered the modal
                var fid = button.data('fid');
                $("#btnDelete").attr('fid', fid);

            });
        }
    </script>
{% endblock %}